package com.bbx.taxi.client.Activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import butterknife.Bind;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.api.gclient.msg.CouponMsg;
import com.bbx.api.sdk.model.comm.returns.line.Cities;
import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.api.sdk.model.passanger.Return.Coupon.CouponList;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Coupons;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata.CarClass;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.Bean.Line;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Adapter.CouponAdapter;
import com.bbx.taxi.client.Adapter.CouponAdapter.ViewHolder;
import com.bbx.taxi.client.Bean.Extra.UseCouponMsg;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_STATUS;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_TYPE;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.Util.CouponUtils;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.RequestUtils;
import com.bbx.taxi.client.Util.ToCity2;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean.ChildCitysBeanX;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean.ChildCitysBeanX.ToCitiesBean;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean.ChildCitysBeanX.ToCitiesBean.ChildCitysBean;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean;

public class UseCouponActivity extends BaseBBXActivity implements CouponMsg,OnItemClickListener{
	@Bind(R.id.listview)
	ListView listview;
	@Bind(R.id.layout_nodata)
	LinearLayout layout_nodata;

	private CouponAdapter mCouponAdapter;
	private List<Coupons> list;
	private LineDB db_line;// 线路数据库
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_usecoupon);
		super.onCreate(savedInstanceState);
		
	}

	@Override
	protected void initView() {
		db_line=new LineDB();
		setTitle(true,getString(R.string.usbcoupon_title), -1, getString(R.string.coupon_no));
		list = new ArrayList<Coupons>();
		mCouponAdapter = new CouponAdapter(this, list);
		listview.setOnItemClickListener(this);
		Bundle mExtras=getIntent().getExtras();
		if(mExtras!=null){
			mCouponAdapter.setCoupon_id(mExtras.getInt(UseCouponMsg.coupon_id));
		}
		else{
			mCouponAdapter.setCoupon_id(0);
		}
		listview.setAdapter(mCouponAdapter);
		if(UseCouponMsg.mCouponUsableBulid!=null)
		RequestUtils.requestCouponUsable(context, UseCouponMsg.mCouponUsableBulid,true);
	}

	@Override
	protected void initData() {
	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	public void notifyDataSetChanged(BaseAdapter adapter) {
		adapter.notifyDataSetChanged();
		onisShowNodata(adapter);
	}

	public void onisShowNodata(BaseAdapter adapter) {
		if (adapter.getCount() == 0) {
			layout_nodata.setVisibility(View.VISIBLE);
		} else {
			layout_nodata.setVisibility(View.GONE);
		}
	}
    @Override
    public void onClick(View v) {
    	switch(v.getId()){
    	case R.id.tv_right:
    		Intent intent = new Intent();
    		intent.putExtra(UseCouponMsg.sum,"0");
    		intent.putExtra(UseCouponMsg.coupon_id, 0);
    		intent.putExtra(UseCouponMsg.coupon_online, false);
    		setResult(UseCouponMsg.resultCode, intent);
    		finish();
    		break;
    	default:
        	super.onClick(v);
    		break;
    	}

    }
    public void setLine_CN(){
		new AsyncTask<Void, Void, Void>() {
			//城际
			 List<String> list_line_num=new ArrayList<String>();
			 List<String> list_line_cn=new ArrayList<String>();
			//市内
			 List<String> list_incity_num=new ArrayList<String>();
			 List<String> list_incity_cn=new ArrayList<String>();
			@Override
			protected Void doInBackground(Void... arg0) {
				list_line_num.addAll(ToCity2.getListLineId(false));
				list_line_cn.addAll(ToCity2.getListLineName(false));
				list_incity_num.addAll(ToCity2.getListLineId(true));
				list_incity_cn.addAll(ToCity2.getListLineName(true));
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
					for(int z=0;z<list.size();z++){
						String name;
						if(list.get(z).getMetadata()!=null){
							List<String> list_line=list.get(z).getMetadata().getUsableline();
							if(list_line!=null){
								String line="";
								for(int i=0;i<list_line.size();i++){
									if(list_line.get(i).trim().equals("*")||list_line.get(i).trim().equals("\"*\"")||list_line.get(i).trim().equals("\"[*]\"")){
										int type=0;
										try{
											type=Integer.parseInt(list.get(z).getMetadata().getUsabletype());
										}catch(Exception e){}
										line=getString(R.string.line_name_all);
										//暂时屏蔽
//		    						//适用于全部
//		    						if(type==-1){
//		    							line=getString(R.string.line_name_all);
//		    						}
//		    						//适用于所有市内
//		    						else if((type&CouponAdapter.int_type[0])>0){
//		    							line=getString(R.string.line_name_all_sn);
//		    						}else {
//		    							line=getString(R.string.line_name_all_cj);
//		    						}

										break;
									}
									else {
										//城际
										for(int j=0;j<list_line_num.size();j++){
											if(list_line.get(i).trim().equals(list_line_num.get(j).trim())){
												if(i!=0&&list_line.size()!=1){
													line+="、";
												}
												line=line+list_line_cn.get(j);
												break;
											}
										}
										//市内
										for(int j=0;j<list_incity_num.size();j++){
											if(list_line.get(i).trim().equals(list_incity_num.get(j).trim())){
												if(i!=0&&list_line.size()!=1){
													line+="、";
												}
												line=line+list_incity_cn.get(j)+"内";
												break;
											}
										}

									}
								}
								//获取不到线路，则默认全部路线
								if(line.equals("")){
									name="";
								}
								else{
									name=String.format(getString(R.string.line_name), line);
								}
								list.get(z).setLine_CN(name);
							}
						}
					}

					for(int i=list.size()-1;i>=0;i--){
						if(list.get(i).getLine_CN()==null){
							list.remove(i);
						}else if(list.get(i).getLine_CN()!=null&&list.get(i).getLine_CN().equals("")){
							list.remove(i);
						}
					}
					notifyDataSetChanged(mCouponAdapter);
				super.onPostExecute(result);
			}
		}.execute();
    }
	@Override
	public void onItemClick(AdapterView<?> arg0, final View v, final int position, long arg3) {
		mCouponAdapter.setCoupon_id(0);
		mCouponAdapter.notifyDataSetChanged();
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				ViewHolder vHollder = (ViewHolder) v.getTag();
				vHollder.layout_top.setBackgroundDrawable(getResources().getDrawable(R.drawable.yhq_bg_down));
				Intent intent = new Intent();
				intent.putExtra(UseCouponMsg.sum, list.get(position).getSum());
				intent.putExtra(UseCouponMsg.coupon_id, list.get(position).getId());
				intent.putExtra(UseCouponMsg.coupon_online, CouponUtils.isMarkOnline(list.get(position).getMetadata().getPaymode()));
				intent.putExtra(UseCouponMsg.coupon_type,list.get(position).getType());
				setResult(UseCouponMsg.resultCode, intent);
				finish();
			}
		}, 10);

	}
	public void onNotifyData(DATA_STATUS data_status, DATA_TYPE data_type,
			int status, Object object) {
		switch (data_type) {
		case COUPONUSABLE:
			if (object != null) {
				CouponList mCouponList = new CouponList();
				JSONArray ja_CouponList;
				try {
					List<Coupons> coupons_list = new ArrayList<Coupons>();
					JSONObject json = new JSONObject((String) object);
					ja_CouponList = json
							.getJSONArray(CouponMsg.msg_coupons);
					for (int i = 0; i < ja_CouponList.length(); i++) {
						Coupons mCoupons = new Coupons();
						JSONObject jo = new JSONObject(ja_CouponList.get(i)
								.toString());
						try {
							mCoupons.setId(Integer.parseInt(jo
									.getString(CouponMsg.msg_id)));
						} catch (Exception e) {
						}
						try {
							mCoupons.setState(Integer.parseInt(jo
									.getString(CouponMsg.msg_state)));
						} catch (Exception e) {
						}
						try {
							mCoupons.setSum(Integer.parseInt(jo
									.getString(CouponMsg.msg_sum)));
						} catch (Exception e) {
						}
						try {
							mCoupons.setTag(jo.getString(CouponMsg.msg_tag));
						} catch (Exception e) {
						}
						try {
							mCoupons.setType(Integer.parseInt(jo
									.getString(CouponMsg.msg_type)));
						} catch (Exception e) {
						}
						//过期时间
						try {
							mCoupons.setExpire_time(jo
									.getString(CouponMsg.msg_expire_time));
						} catch (Exception e) {
						}
						//起始时间
						try {
							mCoupons.setEnable_time(jo
									.getString(CouponMsg.msg_enable_time));
						} catch (Exception e) {
						}
						try {
							mCoupons.setUseLimit(jo
									.getString(CouponMsg.mgs_use_limit));
						} catch (Exception e) {
						}
						//赠送者
						try {
							mCoupons.setGifter(jo.getString(mgs_gifter));
						} catch (Exception e) {
						}
						//赠送时间
						try {
							mCoupons.setGift_time(jo.getString(mgs_gift_time));
						} catch (Exception e) {
						}
						JSONObject jo_metadata = new JSONObject(
								jo.getString(CouponMsg.msg_metadata));
						Metadata mMetadata = new Metadata();

						JSONArray ja_line = new JSONArray(
								jo_metadata
										.getString(CouponMsg.msg_usableline));
						List<String> list_line = new ArrayList<String>();
						for (int j = 0; j < ja_line.length(); j++) {
							String str_line = ja_line.get(j).toString();
							list_line.add(str_line);
						}
						mMetadata.setUsableline(list_line);
						try {
							mMetadata.setUsabletype(jo_metadata
									.getString(CouponMsg.msg_usabletype));
						} catch (Exception e) {
						}
						try {
							mMetadata.setUsableorder(jo_metadata
									.getString(CouponMsg.msg_usableorder));
						} catch (Exception e) {
						}
						try {
							mMetadata.setUsabletime(jo_metadata
									.getString(CouponMsg.msg_usabletime));
						} catch (Exception e) {
						}
						try {
							mMetadata.setPaymode(jo_metadata
									.getString(CouponMsg.msg_paymode));
						} catch (Exception e) {
						}
						try {
							mMetadata.setSum_low_limit(jo_metadata
									.getString(CouponMsg.msg_sum_low));
						} catch (Exception e) {
						}
						try {
							mMetadata.setBusinessType(jo_metadata
									.getString(CouponMsg.mgs_business_type));
						} catch (Exception e) {
						}
						//车型
						try {
							JSONArray ja_car = new JSONArray(
									jo_metadata.getString(CouponMsg.mgs_car_class));
							List<CarClass> list_car = new ArrayList<CarClass>();
							if(ja_car.toString().contains("*")){
								CarClass carclass=new Metadata().new CarClass();
								carclass.setName("*");
								list_car.add(carclass);
							}else{
								for (int j = 0; j < ja_car.length(); j++) {
									JSONObject jo_car = new JSONObject(ja_car.get(j).toString());
									CarClass carclass=new Metadata().new CarClass();
									carclass.setId(jo_car.getString(CouponMsg.mgs_car_id));
									carclass.setName(jo_car.getString(CouponMsg.mgs_car_name));
									list_car.add(carclass);
								}
							}
							mMetadata.setCarClass(list_car);
						
						} catch (Exception e) {
						}
						// //周几限制
						// try {
						// JSONArray ja_time_limit = new JSONArray(
						// jo_metadata.getString(CouponMsg.msg_time_week_use));
						// List<String> list_time_limit = new
						// ArrayList<String>();
						// for (int j = 0; j < ja_time_limit.length(); j++)
						// {
						// String str_time_limit =
						// ja_time_limit.get(j).toString();
						// list_time_limit.add(str_time_limit);
						// }
						// mMetadata.time_week_use=list_time_limit;
						// } catch (Exception e) {
						// }
						// //特殊限制，如周几到周几
						// try{
						// JSONObject json_special = new
						// JSONObject(jo_metadata.getString(CouponMsg.msg_special_time_nouse));
						// SpecialTime mSpecialTime=new SpecialTime();
						// mSpecialTime.start_time=json_special.getLong(CouponMsg.msg_start_time);
						// mSpecialTime.end_time=json_special.getLong(CouponMsg.msg_end_time);
						// mMetadata.special_time_nouse=mSpecialTime;
						// }catch(Exception e){}
						mCoupons.setMetadata(mMetadata);
						coupons_list.add(mCoupons);
					}
					mCouponList.setCouponList(coupons_list);
					list.addAll(mCouponList.getCouponList());
					setLine_CN();
				} catch (JSONException e) {
				}
			}
		
			break;
		}
	}
}
